﻿Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Text.RegularExpressions
Imports FL_8x0.Common
Imports FL_8x0.Model
Imports GalaSoft.MvvmLight
Imports GalaSoft.MvvmLight.CommandWpf
Imports Microsoft.Win32

Namespace FL_8x0.Viewmodel

    Public Class RecordViewModel
        Inherits ViewModelBase

        Private _recordList As DataView               '记录列表视图

        Private _recordModel As RecordModel           '记录查询参数
        Private _loading As Visibility

        Private _searchCommand As RelayCommand        '点击“查询”触发命令

        Private _resetCommand As RelayCommand         '点击“取消”触发命令

        Private _printCommand As RelayCommand         '点击“打印”触发命令

        Private _exportCommand As RelayCommand        '点击“导出”触发命令



        Public Sub New()
            RecordModel = New RecordModel()
            ' FlashShowTable()
            SearchCommand = New RelayCommand(Sub() ExecQuery())
            ResetCommand = New RelayCommand(Sub() ResetQuery())
            PrintCommand = New RelayCommand(Sub() PrintRecord())
            ExportCommand = New RelayCommand(Sub() SaveResult())
            Dim dt As DataTable = New DataTable()
            For i = 0 To 6
                dt.Columns.Add(New DataColumn(g_strResultTitle(i)))
            Next
            dt.Columns.Add(New DataColumn("用户名"))
            For i = 7 To g_strResultTitle.Count - 1
                dt.Columns.Add(New DataColumn(g_strResultTitle(i)))
            Next
            RecordList = dt.DefaultView
            _loading = Visibility.Collapsed
        End Sub


        '=====================================================================
        '函 数 名: SaveResult
        '参    数: 
        '返 回 值:
        '功能描述: 弹出文件选择框，保存测试结果CSV
        '=====================================================================
        Public Sub SaveResult()
            If RecordList.Count > 0 Then  '有测试记录
                '用户保存
                Dim saveDialog As New SaveFileDialog With {
                        .Filter = "CSV文件|*.csv|所有文件|*.*",
                        .FileName = ""
                        }
                saveDialog.ShowDialog()

                If saveDialog.FileName <> "" Then
                    SaveResultCsv(saveDialog.FileName)  '保存全部记录
                End If
            End If
        End Sub


        '=====================================================================
        '函 数 名: SaveResultCsv
        '参    数: strFileName csv文件名
        '返 回 值:
        '功能描述: 将测试结果写入CSV文件
        '=====================================================================
        Private Sub SaveResultCsv(strFileName As String)
            If RecordList.Count > 0 Then  '有测试记录
                Dim swFile = New StreamWriter(strFileName, False, System.Text.Encoding.Default)

                Dim r As Integer
                Dim c As Integer

                Dim strRow As String

                Try
                    strRow = ""
                    For c = 0 To RecordList.Table.Columns.Count - 1
                        strRow &= RecordList.Table.Columns(c).ColumnName & ","
                    Next
                    swFile.Write(strRow & vbCrLf)

                    For r = 0 To RecordList.Count - 1
                        strRow = ""
                        For c = 0 To RecordList.Table.Columns.Count - 1
                            If c = 0 Or c = 1 Or c = 4 Or c = 5 Then
                                strRow &= "'" & RecordList(r)(c) & ","
                            Else
                                strRow &= RecordList(r)(c) & ","
                            End If
                        Next c
                        swFile.Write(strRow & vbCrLf)
                    Next r

                Catch ex As Exception
                    log.WriteLogError("SaveResultCsv():" & strFileName, ex.Message)
                End Try
                swFile.Close()
            End If
        End Sub


        '=====================================================================
        '函 数 名: PrintRecord
        '参    数: 
        '返 回 值:
        '功能描述: 使用xlxs模板打印
        '=====================================================================
        Private Sub PrintRecord()
            If CheckResult() Then
                TestReportPrint(SystemData.g_strExcelPath & "\" & g_udtOtherSet.strTestRecordTemplateName,
                                g_udtOtherSet.strTestRecordSavePath, RecordList.ToTable, Nothing)
            End If
        End Sub

        '=====================================================================
        '函 数 名: ResetQuery
        '参    数: 
        '返 回 值:
        '功能描述: 清空查询产数 执行查询
        '=====================================================================
        Private Sub ResetQuery()
            RecordModel = New RecordModel()
            Call FlashShowTable()
        End Sub

        Public Property RecordList As DataView
            Get
                Return _recordList
            End Get
            Set
                _recordList = Value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property RecordModel As RecordModel
            Get
                Return _recordModel
            End Get
            Set
                _recordModel = Value
                RaisePropertyChanged()
            End Set
        End Property


        Public Property SearchCommand As RelayCommand
            Get
                Return _searchCommand
            End Get
            Set
                _searchCommand = Value
            End Set
        End Property

        Public Property ResetCommand As RelayCommand
            Get
                Return _resetCommand
            End Get
            Set
                _resetCommand = Value
            End Set
        End Property

        Public Property PrintCommand As RelayCommand
            Get
                Return _printCommand
            End Get
            Set
                _printCommand = Value
            End Set
        End Property

        Public Property ExportCommand As RelayCommand
            Get
                Return _exportCommand
            End Get
            Set
                _exportCommand = Value
            End Set
        End Property

        Public Property Loading As Visibility
            Get
                Return _loading
            End Get
            Set(value As Visibility)
                _loading = value
                RaisePropertyChanged()
            End Set
        End Property

        '=====================================================================
        '函 数 名: CheckResult
        '参    数: 
        '返 回 值: 
        '功能描述: 检查[查询结果]是否符合打印要求
        '=====================================================================
        Private Function CheckResult() As Boolean
            If RecordList.Count <= 0 Then
                MsgBox("[查询结果]无数据！")
                Return False
            End If

            '检查是否属于同一个测试报告号
            If RecordList.Count > 1 Then
                Dim i As Int32
                Dim str报告号 As String = RecordList.Item(0).Item("报告号")

                For i = 1 To RecordList.Count - 1
                    If str报告号 <> RecordList.Item(i).Item("报告号") Then
                        MsgBox("[查询结果]不属于同一个[报告号]，无法打印！", vbOKOnly, "错误")
                        Return False
                    End If
                Next
            End If

            Return True
        End Function


        Private Sub ExecQuery()
            If RecordModel.ReportId <> "" Then
                If Not IsNumeric(RecordModel.ReportId) Then
                    log.WriteLogError("输入参数检查", "[报告号]只能含[数字]！")
                    Return
                End If
            End If

            If RecordModel.ProductId <> "" Then
                If Not IsNumeric(RecordModel.ProductId) Then
                    log.WriteLogError("输入参数检查", "[产品号]只能含[数字]！")
                    Return
                End If
            End If

            If RecordModel.RecordId <> "" Then
                If Not IsNumeric(RecordModel.RecordId) Then
                    log.WriteLogError("输入参数检查", "[记录号]只能含[数字]！")
                    Return
                End If
            End If

            Dim rg1 As Regex = New Regex("[=]") '典型的SQL注入攻击 [' or '1' = '1]

            If RecordModel.ProductName <> "" Then
                If rg1.IsMatch(RecordModel.ProductName) Then
                    log.WriteLogError("输入参数检查", "[产品名称]非法输入格式！")
                    Return
                End If
            End If

            If RecordModel.ProductModel <> "" Then
                If rg1.IsMatch(RecordModel.ProductModel) Then
                    log.WriteLogError("输入参数检查", "[产品型号]非法输入格式！")
                    Return
                End If
            End If

            If RecordModel.ProductCode <> "" Then
                If rg1.IsMatch(RecordModel.ProductCode) Then
                    log.WriteLogError("输入参数检查", "[产品编码]非法输入格式！")
                    Return
                End If
            End If

            If RecordModel.StartDate <> "" And RecordModel.EndDate <> "" Then
                If CDate(RecordModel.StartDate) > CDate(RecordModel.EndDate) Then
                    log.WriteLogError("输入参数检查", "[记录时间]起始日期不能大于结束日期！")
                    Return
                End If
            End If

            If RecordModel.UserName <> "" Then
                If Not RecordModel.UserName = SUPER_USER_NAME And Not CheckUserExist(RecordModel.UserName) Then
                    log.WriteLogError("输入参数检查", "[用户名]不存在！")
                    Return
                End If
            End If
            FlashShowTable()
        End Sub

        Public Function QueryTable() As Task(Of DataView)
            Return Task.Run(Function()
                                Dim strConn As String = "Provider=" & SystemData.g_strDatabaseProvider & ";Data Source=" &
                                        SystemData.g_strDatabasePath & "\测试记录.mdb" &
                                        ";Persist Security Info=False;Jet OLEDB:Database Password=" & SUPER_USER_NAME &
                                        SUPER_PASSWORD

                                Dim strWhere As String = ""

                                If RecordModel.ReportId <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "报告号='" & RecordModel.ReportId & "'"
                                End If

                                If RecordModel.ProductId <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "产品号='" & RecordModel.ProductId & "'"
                                End If

                                If RecordModel.RecordId <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "记录号='" & RecordModel.RecordId & "'"
                                End If

                                If RecordModel.ProductName <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "产品名称='" & RecordModel.ProductName & "'"
                                End If

                                If RecordModel.ProductModel <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "产品型号='" & RecordModel.ProductModel & "'"
                                End If

                                If RecordModel.ProductCode <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "产品编码='" & RecordModel.ProductCode & "'"
                                End If

                                If RecordModel.UserName <> "" Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "用户名='" & RecordModel.UserName & "'"
                                End If

                                If Not String.IsNullOrEmpty(RecordModel.StartDate) Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "日期时间 > #" & CDate(RecordModel.StartDate) & "#"
                                End If

                                If Not String.IsNullOrEmpty(RecordModel.EndDate) Then
                                    strWhere &= IIf(strWhere <> "", " and ", "") & "日期时间 < #" & CDate(RecordModel.EndDate).AddDays(1) & "#"
                                End If

                                Dim strCmd As String = "SELECT * FROM 测试记录"

                                If strWhere <> "" Then
                                    strCmd &= " WHERE " & strWhere
                                End If

                                Dim dbAdapter As New OleDbDataAdapter
                                Dim dbTable As New DataTable

                                Try
                                    dbAdapter = New OleDbDataAdapter(strCmd, Database.g_dbConn测试记录)
                                    dbAdapter.Fill(dbTable)
                                    Return dbTable.DefaultView
                                Catch ex As Exception
                                    log.WriteLogError("", ex.Message)
                                    Return New DataView
                                Finally
                                    dbAdapter.Dispose()
                                End Try
                            End Function)
        End Function


        Private Async Sub FlashShowTable()
            Loading = Visibility.Visible
            RecordList = Await QueryTable()
            Loading = Visibility.Collapsed
        End Sub
    End Class
End Namespace